const express = require("express");
const fs = require("fs");
const path = require("path");
const multer = require("multer");
const sqlite3 = require("sqlite3").verbose();
const bodyParser = require("body-parser");

// 读取配置文件
const configPath = path.join(__dirname, "conf", "system.conf");
const config = JSON.parse(fs.readFileSync(configPath, "utf8"));

// 确保目录存在
const ensureDirectoryExists = (dir) => {
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir, { recursive: true });
  }
};

// 初始化目录
ensureDirectoryExists(path.join(__dirname, "db"));
ensureDirectoryExists(path.join(__dirname, "static", "apks"));
ensureDirectoryExists(path.join(__dirname, "cache"));

// 初始化SQLite数据库
const dbPath = path.join(__dirname, "db", "versions.db");
const db = new sqlite3.Database(dbPath);

// 创建表（如果不存在）
db.serialize(() => {
  db.run(`
    CREATE TABLE IF NOT EXISTS versions (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      version_type TEXT NOT NULL,
      major_version INTEGER NOT NULL,
      minor_version INTEGER NOT NULL,
      patch_version INTEGER NOT NULL,
      force_update_range TEXT,
      publish_time TEXT NOT NULL,
      update_info TEXT NOT NULL,
      apk_url TEXT NOT NULL,
      is_active INTEGER DEFAULT 1,
      created_at TEXT NOT NULL
    )
  `);
});

// 配置Multer处理文件上传
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, path.join(__dirname, "static", "apks"));
  },
  filename: (req, file, cb) => {
    const { version_type, major_version, minor_version, patch_version } =
      req.body;
    const ext = path.extname(file.originalname);
    const apkFilename = `${config.apkName}-${version_type}-${major_version}.${minor_version}.${patch_version}.apk`;
    const filename = `${config.apkName}-${version_type}-${major_version}.${minor_version}.${patch_version}${ext}`;
    cb(null, filename);
  },
});

const upload = multer({
  storage: storage,
  fileFilter: (req, file, cb) => {
    if (path.extname(file.originalname) !== ".apk") {
      return cb(new Error("Only APK files are allowed"));
    }
    cb(null, true);
  },
});

// 创建Express应用
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// 静态资源服务
app.use("/static", express.static(path.join(__dirname, "static")));

// 处理HTML模板
const processHtmlTemplate = () => {
  const templatePath = path.join(__dirname, "html", "index.html");
  let html = fs.readFileSync(templatePath, "utf8");

  // 替换模板中的变量
  html = html
    .replace(/\{\{configPort\}\}/g, config.configPort)
    .replace(/\{\{protocol\}\}/g, config.protocol)
    .replace(/\{\{ip\}\}/g, config.ip);

  // 写入缓存目录
  const cachePath = path.join(__dirname, "cache", "index.html");
  fs.writeFileSync(cachePath, html);
};
// 处理下载页面HTML模板
const processDownloadHtmlTemplate = () => {
  const templatePath = path.join(__dirname, "html", "download.html");
  let html = fs.readFileSync(templatePath, "utf8");

  // 替换模板中的变量
  html = html
    .replace(/\{\{protocol\}\}/g, config.protocol)
    .replace(/\{\{ip\}\}/g, config.ip)
    .replace(/\{\{configPort\}\}/g, config.configPort)
    .replace(/\{\{appName\}\}/g, config.appName || "我的应用")
    .replace(
      /\{\{appDescription\}\}/g,
      config.appDescription || "欢迎下载我们的应用"
    );

  // 写入缓存目录
  const cachePath = path.join(__dirname, "cache", "download.html");
  fs.writeFileSync(cachePath, html);
};
// 初始化时处理HTML模板
processHtmlTemplate();
processDownloadHtmlTemplate(); // 新增这行
// API路由

// 获取所有版本
// app.get("/api/versions", (req, res) => {
//   db.all("SELECT * FROM versions ORDER BY created_at DESC", [], (err, rows) => {
//     if (err) {
//       return res.status(500).json({ error: err.message });
//     }
//     res.json(rows);
//   });
// });

// 添加新版本
app.post("/api/versions", upload.single("apk"), (req, res) => {
  const {
    version_type,
    major_version,
    minor_version,
    patch_version,
    force_update_range,
    update_info,
  } = req.body;

  const publish_time = new Date().toISOString().split("T")[0];
  const created_at = new Date().toISOString();

  // 修改这里：只存储相对路径
  const apkFilename = `${config.apkName}-${version_type}-${major_version}.${minor_version}.${patch_version}.apk`;
  const apkUrl = `static/apks/${apkFilename}`; // 只存储相对路径

  const sql = `
    INSERT INTO versions (
      version_type, major_version, minor_version, patch_version, 
      force_update_range, publish_time, update_info, apk_url, created_at
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
  `;

  const params = [
    version_type,
    parseInt(major_version),
    parseInt(minor_version),
    parseInt(patch_version),
    force_update_range,
    publish_time,
    update_info,
    apkUrl, // 使用相对路径
    created_at,
  ];

  db.run(sql, params, function (err) {
    if (err) {
      return res.status(500).json({ error: err.message });
    }
    res.json({
      id: this.lastID,
      message: "Version added successfully",
    });
  });
});

// 更新版本状态
app.put("/api/versions/:id/status", (req, res) => {
  const { id } = req.params;
  const { is_active } = req.body;

  db.run(
    "UPDATE versions SET is_active = ? WHERE id = ?",
    [is_active ? 1 : 0, id],
    function (err) {
      if (err) {
        return res.status(500).json({ error: err.message });
      }
      res.json({
        changes: this.changes,
        message: "Version status updated successfully",
      });
    }
  );
});

// 删除版本
app.delete("/api/versions/:id", (req, res) => {
  const { id } = req.params;

  // 先获取APK URL以便删除文件
  db.get("SELECT apk_url FROM versions WHERE id = ?", [id], (err, row) => {
    if (err) {
      return res.status(500).json({ error: err.message });
    }

    if (!row) {
      return res.status(404).json({ error: "Version not found" });
    }

    // 删除数据库记录
    db.run("DELETE FROM versions WHERE id = ?", [id], function (err) {
      if (err) {
        return res.status(500).json({ error: err.message });
      }

      // 删除APK文件
      const apkPath = path.join(
        __dirname,
        "static",
        "apks",
        path.basename(row.apk_url)
      );
      if (fs.existsSync(apkPath)) {
        fs.unlinkSync(apkPath);
      }

      res.json({
        changes: this.changes,
        message: "Version deleted successfully",
      });
    });
  });
});
const processVersionForResponse = (version) => {
  if (!version) return version;

  return {
    ...version,
    // 拼接完整的下载URL
    apk_url: `${version.apk_url}`,
  };
};

// 获取版本列表（支持只获取已启用的版本）
app.get("/api/versions", (req, res) => {
  const { active_only } = req.query;
  let query = "SELECT * FROM versions ";
  const params = [];

  if (active_only === "true") {
    query += "WHERE is_active = 1 ";
  }

  query += "ORDER BY created_at DESC";

  db.all(query, params, (err, rows) => {
    if (err) {
      return res.status(500).json({ error: err.message });
    }
    // 处理每个版本的URL
    res.json(rows.map(processVersionForResponse));
  });
});

// 获取最新版本（支持按类型筛选）
app.get("/api/versions/latest", (req, res) => {
  const { type } = req.query;
  let query = "SELECT * FROM versions WHERE is_active = 1 ";
  const params = [];

  if (type) {
    query += "AND version_type = ? ";
    params.push(type);
  }

  query +=
    "ORDER BY major_version DESC, minor_version DESC, patch_version DESC LIMIT 1";

  db.get(query, params, (err, row) => {
    if (err) {
      return res.status(500).json({ error: err.message });
    }
    // 处理URL
    res.json(processVersionForResponse(row));
  });
});

// 提供管理页面
app.get("/", (req, res) => {
  res.sendFile(path.join(__dirname, "cache", "index.html"));
});
// 提供下载页面
app.get("/download", (req, res) => {
  res.sendFile(path.join(__dirname, "cache", "download.html"));
});

// 启动服务
app.listen(config.configPort, () => {
  console.log(
    `Config service running at ${config.protocol}${config.ip}:${config.configPort}`
  );
  console.log(
    `Client Download Page is Publish at ${config.protocol}${config.ip}:${config.configPort}/download`
  );
  console.log(
    `APK static service running at ${config.protocol}${config.ip}:${config.configPort}/static`
  );
});
